package com.diy.ibatis.Sqlsession;

import com.diy.ibatis.cfg.Mapper;
import com.diy.ibatis.utils.Executor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Map;

public class MapperProxy implements InvocationHandler {
    //map的key是全限定类型+方法名
    private Map<String,Mapper> mappers;
    private Connection conn;
    public   MapperProxy(Map<String, Mapper> mappers, Connection conn){
        this.mappers=mappers;
        this.conn=conn;
    }
    /**
     * 用于代理方法的增强，调用selectlist方法
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //1获取方法名
        String methodName= method.getName();
        //2获取方法所在的类的名称
        String className=method.getDeclaringClass().getName();
        //3组合key
        String key=className+"."+methodName;
        //4获取mappers 中的mapper对象
        Mapper mapper=mappers.get(key);
        //5判断是否有mapper
        if (mapper == null){
            System.out.println("参数有问题");
            //RuntimeException 异常 它执行 程序停止
           throw new IllegalArgumentException("传入参数有问题");
        }
        //6调用工具类 查询所有
        return new Executor().selectList(mapper,conn);
    }
}
